<?php

namespace Util;


use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Stream;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/27
 * Time: 16:11
 */
class Http
{
    const TIMEOUT = 20;

    /**
     * @param $url
     * @param $data
     * @param array $header
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public static function post($url, $data = [], $header = [])
    {
        $client = new Client(['verify' => false, 'http_errors' => false]);
        $request = new Request('POST', $url, $header);
        return $client->send($request, ['form_params' => $data, 'debug' => false, 'timeout' => self::TIMEOUT]);
    }

    /**
     *  发送xml
     * @param $url
     * @param $xml
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public static function postXml($url, $xml)
    {
        $client = new Client(['verify' => false, 'timeout' => self::TIMEOUT]);
        $request = new Request('POST', $url, []);
        return $client->send($request, ['body' => stream_for($xml), 'timeout' => self::TIMEOUT]);
    }

    /**
     *  异步post
     * @param $url
     * @param $data
     * @param array $header
     */
    public static function asyncPost($url, $data = [], $header = [])
    {
        $client = new Client(['verify' => false, 'http_errors' => false, 'timeout' => self::TIMEOUT]);
        $request = new Request('POST', $url, $header);
        return $client->sendAsync($request, ['form_params' => $data, 'timeout' => self::TIMEOUT]);
    }

    /**
     * @param $url
     * @param array $header
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public static function get($url, $header = [])
    {
        $client = new Client(['http_errors' => false, 'timeout' => self::TIMEOUT]);
        $request = new Request('GET', $url, $header, null);
        return $client->send($request, ['timeout' => self::TIMEOUT]);
    }

    public static function upload($url, $multipart, $header = [])
    {
        $client = new Client(['verify' => false, 'http_errors' => false, 'timeout' => self::TIMEOUT]);
        $request = new Request('POST', $url, $header, null);
        return $client->send($request, ['multipart' => $multipart, 'timeout' => self::TIMEOUT]);
    }


    /**
     *  发送yaml
     * @param $url
     * @param $data
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public static function postJson2($url, $data, $headers = [])
    {
        $client = new Client(['verify' => false, 'http_errors' => false, 'timeout' => self::TIMEOUT, 'debug' => false]);
        $default = ['Content-Type' => 'application/json'];
        $headers = array_merge($headers, $default);

        $request = new Request('POST', $url, $headers);
        return $client->send($request, ['body' => stream_for($data), 'timeout' => self::TIMEOUT]);
    }


}
